import { Form, Input, Button, Upload, message } from "antd";
import React, { Component, ReactNode } from "react";
import { Editor } from "react-draft-wysiwyg";
import { convertToRaw, EditorState, ContentState } from "draft-js";
import draftToHtml from "draftjs-to-html";
import htmlToDraft from "html-to-draftjs";
import "react-draft-wysiwyg/dist/react-draft-wysiwyg.css";
import { UploadOutlined } from "@ant-design/icons";
import { instance } from '../../utils/request';
import { url } from "inspector";
import '../../assets/style/common.scss'
interface EditGoodFormProps {
  data: any;
  visible?: boolean;
  close?: () => void;
  closeModal: () => void; // 将closeModal方法作为props传递给子组件
}

class EditGoodForm extends Component<EditGoodFormProps> {
  state = {
    // 富文本存储的值
    editorText: "",
    // 编辑的父文本值
    editorState: EditorState.createEmpty(), // 初始化为一个空的编辑器状态
  };
  // 执行更新操作
  onFinish = (values: any) => {
    console.log(values);
    let params = {
      goods_name: values.goods_name,
      goods_price: values.goods_price,
      goods_number: values.goods_number,
      goods_weight: values.goods_weight,
      goods_cat: "1,2,3",
      // 富文本信息
      goods_introduce: this.state.editorText,
      //图片后续处理 1. 不等于underfined 表示已经上传了
      goods_small_logo:
        values.goods_small_logo[0].response !== undefined
          ? values.goods_small_logo[0].response.data.data.url
          : values.goods_small_logo[0].name,
    };
    instance
      .put(`/goods/${this.props.data.goods_id}`, params)
      .then((res) => {
        message.success("修改商品成功!");
        this.props.closeModal();
      })
      .catch((error) => {
        console.log("error=", error);
      });
  };

  fromRef = React.createRef<any>();
  // 获取焦点引用
  setDomEditorRef = React.createRef<any>();

  componentDidMount(): void {
    // 重新进行渲染
    // 获取 父级组件传递过来的值
    const {
      goods_name,
      goods_price,
      goods_number,
      goods_weight,
      goods_introduce,
      goods_small_logo,
    } = this.props.data;

    // 填充表单，获取数据
    this.fromRef.current.setFieldsValue({
      goods_name,
      goods_price,
      goods_number,
      goods_weight,
      goods_small_logo: [{ name: goods_small_logo, url: goods_small_logo }],
    });
    // 获取焦点
    this.setDomEditorRef.current.focusEditor();
    this.setState({
      editorState: this.transformHtmlToDraftState(goods_introduce),
    });
  }
  transformHtmlToDraftState = (html = "") => {
    const blocksFromHtml = htmlToDraft(html);
    const { contentBlocks, entityMap } = blocksFromHtml;
    const contentState = ContentState.createFromBlockArray(
      contentBlocks,
      entityMap
    );
    return EditorState.createWithContent(contentState);
  };

  onFinishFailed = () => {};
  handleCustomRequest = (options:any) => {
    const { file, onError, onSuccess } = options;
    const ext = file.name.split('.')[1];
    if (!['jpg', 'jpeg', 'png'].includes(ext)) {
      message.error('请上传jpg、jpeg、png格式的图片');
      onError('File format not supported');
      return;
    }
    const formData = new FormData();
    formData.append('file', file);

    instance.post("/upload", formData)
      .then((response) => {
        onSuccess(response, file);
      })
      .catch((error) => {
        onError(error);
      });
  };

  normFile = (e: any) => {
    console.log("Upload event:", e);
    if (Array.isArray(e)) {
      return e;
    }
    const arr = [];
    arr.push(e.fileList[e.fileList.length - 1]);

    return e && arr;
  };

  // 富文本编辑器的内容
  onEditorStateChange = (editorState: any) => {
    // 讲富文本编辑器内容转换为字符串
    let html = draftToHtml(convertToRaw(editorState.getCurrentContent()));
    // console.log(html);

    this.setState({
      editorText: html,
      editorState: editorState,
    });
  };

  render() {
    return (
      <div>
        <Form
          onFinish={this.onFinish}
          onFinishFailed={this.onFinishFailed}
          ref={this.fromRef}
        >
          <Form.Item
            label="商品名称"
            name="goods_name"
            rules={[{ required: true, message: "请输入商品名称" }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="商品价格"
            name="goods_price"
            rules={[{ required: true, message: "请输入商品价格" }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="商品重量"
            name="goods_weight"
            rules={[{ required: true, message: "请输入商品重量" }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="商品数量"
            name="goods_number"
            rules={[{ required: true, message: "请输入商品数量" }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="商品图片"
            name="goods_small_logo"
            rules={[{ required: true, message: "请上传商品图片" }]}
            valuePropName="fileList"
            getValueFromEvent={this.normFile}
          >
            <Upload
            customRequest={this.handleCustomRequest}
            listType="picture"
            >
              <Button icon={<UploadOutlined />}>上传图片</Button>
            </Upload>
          </Form.Item>

          <Form.Item
            label="商品详情"
            name="goods_introduce"
            rules={[
              {
                validator: (rule, value, callback) => {
                  const content = this.state.editorState.getCurrentContent();
                  if (value === "" || content.hasText()) {
                    callback();
                  } else {
                    callback("请输入商品详情");
                  }
                },
              },
            ]}
          >
            <div  className="editor-container">
              <Editor
                ref={this.setDomEditorRef}
                toolbarClassName="toolbarClassName"
                wrapperClassName="wrapperClassName"
                editorClassName="editorClassName"
                onEditorStateChange={this.onEditorStateChange}
                editorState={this.state.editorState}
              />
            </div>
          </Form.Item>

          <Form.Item style={{float:'right',marginLeft:'10px'}}>
            <Button type="primary" htmlType="submit">
              提交
            </Button>
          </Form.Item>
        </Form>
      </div>
    );
  }
}

export default EditGoodForm;
